package binary_tree;

public class BinaryTreeDemo {
    public static void main(String[] args) {
        BinaryTree bt = new BinaryTree();
        Node n1 = new Node(1, "a");
        Node n2 = new Node(2, "b");
        Node n3 = new Node(3, "c");
        Node n4 = new Node(4, "d");
        // 手动创建
        bt.root = n1;
        bt.root.left = n2;
        bt.root.right = n3;
        n3.right = n4;
        // 三种遍历
        System.out.println("前序遍历");
        bt.preOrder();
        System.out.println("中序遍历");
        bt.infixOrder();
        System.out.println("后序遍历");
        bt.postOrder();
    }
}

class BinaryTree {
    public Node root;

    // 前序遍历
    public void preOrder() {
        if (this.root != null) {
            this.root.preOrder();
        } else {
            System.out.println("二叉树为空");
        }
    }

    // 中序遍历
    public void infixOrder() {
        if (this.root != null) {
            this.root.infixOrder();
        } else {
            System.out.println("二叉树为空");
        }
    }

    // 后序遍历
    public void postOrder() {
        if (this.root != null) {
            this.root.postOrder();
        } else {
            System.out.println("二叉树为空");
        }
    }
}

class Node {
    int id;
    String name;
    Node left;
    Node right;

    Node(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Node[id=" + id + ", name=" + name + "]";
    }

    // 前序遍历
    public void preOrder() {
        System.out.println(this);
        if (left != null) {
            this.left.preOrder();
        }
        if (right != null) {
            this.right.preOrder();
        }
    }

    // 中序遍历
    public void infixOrder() {
        if (left != null) {
            this.left.preOrder();
        }
        System.out.println(this);
        if (right != null) {
            this.right.preOrder();
        }
    }

    // 后序遍历
    public void postOrder() {
        if (left != null) {
            this.left.postOrder();
        }
        if (right != null) {
            this.right.postOrder();
        }
        System.out.println(this);
    }
}